<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { StashArrowReply } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTooltip,
} from 'element-plus';

import {
  getSalesChannelApi,
  getSupplierSaleSummeryDetailApi,
  getSuppliersListApi,
} from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import {
  getCommonShortcuts,
  getUrlParam,
  isNotNull,
  updateURLParams,
} from '#/utils';

const { locale } = useI18n();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});
const submitForm: any = reactive({
  timeRange: [], // 统计日期
  supplierType: true, // 供应商类型
  supplier: [], // 供应商
  salesChannel: [], // 销售渠道
  salesType: '全部', // 销售类型
  publisherType: '全部', // 供应商类型
  publisherName: '', // 供应商
  pageNo: 1, // 页码
  pageSize: 50, // 每页条数
});

const lastCollectDate = ref<any>(null);

const allData = ref<any[]>([]);
const tableData = ref<any[]>([]);

// 筛选表单
const filterForm = reactive<any>({
  // 文本字段筛选
  serialNo: '',
  bookName: '',
  barCode: '',
  // 数字字段范围筛选
  price: { min: null, max: null },
  saleNum: { min: null, max: null },
  saleMayang: { min: null, max: null },
  saleShiyang: { min: null, max: null },
  saleDiscount: { min: null, max: null },
  pubSettMoney: { min: null, max: null },
  expressMoney: { min: null, max: null },
  platformMoney: { min: null, max: null },
  saleSettlementProfit: { min: null, max: null },
  settlementGrossProfitMargin: { min: null, max: null },
});

// 通用数字范围检查函数
function checkNumberRange(itemValue: any, filterMin: any, filterMax: any) {
  const num = Number(itemValue);
  return !(
    (isNotNull(filterMin) && num < filterMin) ||
    (isNotNull(filterMax) && num > filterMax)
  );
}

// 筛选后的数据
const filteredData = computed(() => {
  return allData.value.filter((item) => {
    // 文本字段模糊筛选
    if (
      filterForm.serialNo &&
      !String(item.serialNo)
        .toLowerCase()
        .includes(filterForm.serialNo.toLowerCase())
    ) {
      return false;
    }

    // 书名多分词筛选
    if (filterForm.bookName) {
      const keywords = filterForm.bookName
        .trim()
        .split(/\s+/)
        .filter((keyword: string) => keyword.length > 0);

      if (keywords.length > 0) {
        const bookName = String(item.bookName).toLowerCase();
        // 所有关键词都必须匹配
        const allKeywordsMatch = keywords.every((keyword: string) =>
          bookName.includes(keyword.toLowerCase()),
        );
        if (!allKeywordsMatch) {
          return false;
        }
      }
    }

    if (
      filterForm.barCode &&
      !String(item.barCode)
        .toLowerCase()
        .includes(filterForm.barCode.toLowerCase())
    ) {
      return false;
    }

    // 需要检查的数字字段列表
    const numberFields = [
      'price',
      'saleNum',
      'saleMayang',
      'saleShiyang',
      'saleDiscount',
      'pubSettMoney',
      'expressMoney',
      'platformMoney',
      'saleSettlementProfit',
      'settlementGrossProfitMargin',
    ];

    // 条形码筛选
    if (
      filterForm.barCode &&
      !String(item.barCode)
        .toLowerCase()
        .includes(filterForm.barCode.toLowerCase())
    ) {
      return false;
    }

    // 数字字段筛选
    for (const field of numberFields) {
      if (
        !checkNumberRange(
          item[field],
          filterForm[field]?.min,
          filterForm[field]?.max,
        )
      ) {
        return false;
      }
    }

    return true;
  });
});

const updateTableData = () => {
  const start = (submitForm.pageNo - 1) * submitForm.pageSize;
  const end = start + submitForm.pageSize;
  tableData.value = filteredData.value.slice(start, end);
};

// 监听筛选数据变化
watch(
  filteredData,
  () => {
    total.value = filteredData.value.length;
    submitForm.pageNo = 1;
    updateTableData();
  },
  { deep: true },
);

const searchLoading = ref(false);

const onSubmit = async () => {
  try {
    searchLoading.value = true;
    const params = {
      startDate: submitForm.timeRange[0],
      endDate: submitForm.timeRange[1],
      ispubgroup: submitForm.supplierType,
      publishernames: submitForm.supplier,
      channelnames: submitForm.salesChannel,
      saletype: submitForm.salesType === '全部' ? '' : submitForm.salesType,
      publishername: submitForm.publisherName,
      publishertype:
        submitForm.publisherType === '全部' ? '' : submitForm.publisherType,
    };
    const { data, systemLastDate } =
      await getSupplierSaleSummeryDetailApi(params);
    lastCollectDate.value = systemLastDate;

    data.forEach((item: any) => {
      item.saleDiscount =
        Math.floor((+item.saleShiyang / +item.saleMayang) * 10_000) / 100;
      item.purchaseDiscount =
        Math.floor((+item.pubCostMoney / +item.saleMayang) * 10_000) / 100;
      // 开单毛利 = 实洋 - 进货成本 - 快递 - 平台扣点
      item.saleGrossProfit =
        item.saleShiyang -
        item.pubCostMoney -
        item.expressMoney -
        item.platformMoney;
      // 结算毛利 = 实洋 - 预估成本 - 快递 - 平台扣点
      item.saleSettlementProfit =
        item.saleShiyang -
        item.pubSettMoney -
        item.expressMoney -
        item.platformMoney;
      item.saleGrossProfitMargin =
        Math.floor(
          (+item.saleGrossProfit / Number(item.saleShiyang)) * 10_000,
        ) / 100;

      item.settlementGrossProfitMargin =
        Math.floor(
          (+item.saleSettlementProfit / Number(item.saleShiyang)) * 10_000,
        ) / 100;
    });
    const nfArr = new Set([
      'barCode',
      'bookName',
      'publisher',
      'saleGrossProfitMargin',
      'saleNum',
      'serialNo',
    ]);
    data.forEach((item: any) => {
      for (const key in item) {
        if (!nfArr.has(key)) {
          item[key] =
            String(item[key]) === 'infinity' || item[key] === 'NaN'
              ? '-'
              : item?.[key]?.toFixed(2) || '-';
        }
      }
    });
    allData.value = data;
    total.value = data.length;
    submitForm.pageNo = 1;
    updateTableData();
    applyAutoSort();
  } catch (error: any) {
    console.error(error);
  } finally {
    searchLoading.value = false;
  }
};

const applyAutoSort = () => {
  const sortBy = getUrlParam('sortBy');
  const sortOrder = getUrlParam('sortOrder');

  if (sortBy && sortOrder) {
    // 设置降序排序
    const columnIndex = tableRef.value?.columns?.findIndex(
      (item: any) => item.property === sortBy,
    );
    const icon = tableRef.value?.$el?.querySelectorAll(`th i.${sortOrder}`)?.[
      columnIndex
    ];
    if (icon) {
      icon.click();
    }
    handleSortChange({ prop: sortBy, order: sortOrder });
  }
};

const total = ref(0);

const handleSizeChange = (val: number) => {
  submitForm.pageSize = val;
  submitForm.pageNo = 1;
  updateTableData();
};
const handleCurrentChange = (val: number) => {
  submitForm.pageNo = val;
  updateTableData();
};

const router = useRouter();
const route = useRoute();

onMounted(() => {
  const kRaw = route.query.k;
  if (!kRaw) {
    router.push('/404');
    return;
  }
  dealUrlParams(kRaw);
  getSupplierType();
  getSalesChannelType();
  onSubmit();
});

const dealUrlParams = (params: any) => {
  const p = JSON.parse(params);
  submitForm.timeRange = p.timeRange;
  submitForm.supplierType = p.supplierType;
  submitForm.salesType = p.salesType;
  submitForm.supplier = p.supplier;
  submitForm.salesChannel = p.salesChannel;
  submitForm.publisherName = p.publisherName;
  submitForm.pageNo = p.pageNo;
  submitForm.pageSize = p.pageSize;
  submitForm.publisherType = p.publisherType;
};

const getSupplierType = async () => {
  const { data } = await getSuppliersListApi();
  options.supplierOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};
const getSalesChannelType = async () => {
  const { data } = await getSalesChannelApi();
  options.salesChannelOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};

const options = reactive<any>({
  supplierOptions: [],
  salesChannelOptions: [],
  salesTypeOptions: [
    {
      label: '全部',
      value: '全部',
    },
    {
      label: '经销',
      value: '经销',
    },
    {
      label: '分销',
      value: '分销',
    },
  ],
});

const tableRef = ref<any>(null);

const sortBy = ref('');
const sortOrder = ref('');
const handleSortChange = ({ prop, order }: any) => {
  updateURLParams({
    sortBy: prop,
    sortOrder: order,
  });
  sortBy.value = prop;
  sortOrder.value = order;
  if (!order) return;
  const notNumber = new Set(['barCode', 'bookName', 'serialNo']);
  allData.value.sort((a: any, b: any) => {
    const aVal = a[prop];
    const bVal = b[prop];
    if (notNumber.has(prop)) {
      return order === 'ascending'
        ? String(aVal).localeCompare(String(bVal))
        : String(bVal).localeCompare(String(aVal));
    } else {
      return order === 'ascending'
        ? Number(aVal) - Number(bVal)
        : Number(bVal) - Number(aVal);
    }
  });
  updateTableData();
};

// 筛选相关函数
const onSubmit2 = () => {
  onSubmit();
};

const onReset = () => {
  // 重置所有筛选条件
  Object.keys(filterForm).forEach((key) => {
    if (typeof filterForm[key] === 'string') {
      filterForm[key] = '';
    } else if (
      typeof filterForm[key] === 'object' &&
      filterForm[key] !== null
    ) {
      filterForm[key].min = null;
      filterForm[key].max = null;
    }
  });
  updateTableData();
};

const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns } = param;
  const sums: any = [];
  const keyIndex: any = {};
  columns.forEach((column: any, index: number) => {
    keyIndex[column.property] = index;
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const property = column.property;
    if (!property) {
      sums[index] = 'N/A';
      return;
    }

    // 非数字字段显示N/A
    const nonNumericFields = [
      'serialNo',
      'bookName',
      'barCode',
      'settlementGrossProfitMargin',
      'saleDiscount',
    ];
    if (nonNumericFields.includes(property)) {
      sums[index] = '';
      return;
    }

    // 数字字段进行汇总
    const values = filteredData.value.map((item: any) =>
      String(item[property]) === 'NaN' ? 0 : Number(item[property]),
    );

    if (values.length > 0) {
      const sum = values.reduce((a: number, b: number) => a + b, 0);
      sums[index] = sum.toFixed(2);
    } else {
      sums[index] = '0.00';
    }
  });
  sums[keyIndex.settlementGrossProfitMargin] =
    Math.floor(
      (sums[keyIndex.saleSettlementProfit] / sums[keyIndex.saleShiyang]) *
        10_000,
    ) / 100;
  sums[keyIndex.saleDiscount] =
    Math.floor(
      (sums[keyIndex.saleShiyang] / sums[keyIndex.saleMayang]) * 10_000,
    ) / 100;
  sums[keyIndex.saleNum] = Number(sums[keyIndex.saleNum]).toFixed(0);
  return sums;
};
</script>

<template>
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <CollapsibleCard>
      <ElForm :model="submitForm" @keyup.enter="onSubmit" label-position="top">
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplierType')">
          <ElSelect
            v-model="submitForm.publisherType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption label="全部" value="全部" />
            <ElOption label="新书" value="新书" />
            <ElOption label="特价" value="特价" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="供应商分组">
          <ElSelect
            v-model="submitForm.supplierType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption label="按大社" :value="true" />
            <ElOption label="按小社" :value="false" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplier')">
          <ElSelect
            v-model="submitForm.supplier"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesChannel')">
          <ElSelect
            v-model="submitForm.salesChannel"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesChannelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesType')">
          <ElSelect
            v-model="submitForm.salesType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem>
          <div class="flex w-full justify-center gap-2">
            <ElButton type="primary" @click="onSubmit2">
              {{ $t('views.common.filter') }}
            </ElButton>
            <ElButton @click="onReset">
              {{ $t('views.common.reset') }}
            </ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>
    <ElCard class="relative !ml-1 h-full flex-1 !overflow-auto">
      <div
        class="hover:text-primary absolute right-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <div
        class="hover:text-primary absolute left-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{ `${submitForm.publisherName}  ${$t('views.report.salesDetails')}` }}
      </h2>
      <h2 class="tems-center mb-2 flex justify-center text-base font-bold"></h2>
      <div class="flex justify-end text-xs">
        <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
        <div class="mr-4">
          {{ $t('views.common.statisticalDate') }}：<span
            v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
          >
            {{ `${submitForm.timeRange[0]}` }} -
            {{ `${submitForm.timeRange[1]}` }}
          </span>
        </div>
        <CurrentDateTime />
      </div>
      <ElTable
        :data="tableData"
        border
        ref="tableRef"
        @sort-change="handleSortChange"
        v-loading="searchLoading"
        :show-summary="true"
        :summary-method="getSummaries"
      >
        <ElTableColumn
          prop="serialNo"
          :label="$t('views.common.serialNo')"
          min-width="100"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="serialNo" min-width="100">
            <template #header>
              <div>
                <ElInput v-model="filterForm.serialNo" clearable />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>

        <ElTableColumn
          prop="bookName"
          :label="$t('views.common.bookName')"
          min-width="200"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="bookName" min-width="200">
            <template #header>
              <div>
                <ElInput v-model="filterForm.bookName" clearable />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="barCode"
          :label="$t('views.common.ISBN')"
          min-width="120"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="barCode" min-width="120">
            <template #header>
              <div>
                <ElInput v-model="filterForm.barCode" clearable />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="price"
          :label="$t('views.common.price')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="price" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.price.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.price.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.price.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.price.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="saleNum"
          :label="$t('views.common.totalVolumeNumber')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="saleNum" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.saleNum.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleNum.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.saleNum.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleNum.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="saleMayang"
          :label="$t('views.common.totalFixedPrice')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="saleMayang" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.saleMayang.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleMayang.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.saleMayang.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleMayang.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="saleShiyang"
          :label="$t('views.common.totalSalePrice')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="saleShiyang" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.saleShiyang.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleShiyang.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.saleShiyang.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleShiyang.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="saleDiscount"
          :label="$t('views.common.saleDiscount')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.saleDiscount') }}
                </span>
                <template #content>
                  <div style="width: auto">总实洋/总码洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <ElTableColumn prop="saleDiscount" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.saleDiscount.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleDiscount.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.saleDiscount.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.saleDiscount.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="pubSettMoney"
          :label="$t('views.common.estimatedCost')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="pubSettMoney" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.pubSettMoney.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.pubSettMoney.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.pubSettMoney.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.pubSettMoney.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="expressMoney"
          :label="$t('views.common.expressDeliveryCost')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="expressMoney" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.expressMoney.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.expressMoney.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.expressMoney.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.expressMoney.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="platformMoney"
          :label="$t('views.common.platformDeductionPoints')"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <ElTableColumn prop="platformMoney" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="filterForm.platformMoney.min ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.platformMoney.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="filterForm.platformMoney.max ?? undefined"
                  @update:model-value="
                    (val) => (filterForm.platformMoney.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="saleSettlementProfit"
          label="毛利"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer"> 毛利 </span>
                <template #content>
                  <div style="width: auto">
                    实洋 - 预估成本 - 快递成本 - 平台扣点
                  </div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <ElTableColumn prop="saleSettlementProfit" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="
                    filterForm.saleSettlementProfit.min ?? undefined
                  "
                  @update:model-value="
                    (val) => (filterForm.saleSettlementProfit.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="
                    filterForm.saleSettlementProfit.max ?? undefined
                  "
                  @update:model-value="
                    (val) => (filterForm.saleSettlementProfit.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
        <ElTableColumn
          prop="settlementGrossProfitMargin"
          label="毛利率"
          align="right"
          header-align="center"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer"> 毛利率 </span>
                <template #content>
                  <div style="width: auto">毛利/销售实洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
          <ElTableColumn prop="settlementGrossProfitMargin" align="right">
            <template #header>
              <div class="flex gap-2">
                <ElInput
                  :model-value="
                    filterForm.settlementGrossProfitMargin.min ?? undefined
                  "
                  @update:model-value="
                    (val) =>
                      (filterForm.settlementGrossProfitMargin.min = val ?? null)
                  "
                  type="number"
                />
                <ElInput
                  :model-value="
                    filterForm.settlementGrossProfitMargin.max ?? undefined
                  "
                  @update:model-value="
                    (val) =>
                      (filterForm.settlementGrossProfitMargin.max = val ?? null)
                  "
                  type="number"
                />
              </div>
            </template>
          </ElTableColumn>
        </ElTableColumn>
      </ElTable>
      <ElPagination
        :current-page="submitForm.pageNo"
        :page-size="submitForm.pageSize"
        :page-sizes="[50, 500]"
        class="mt-4 flex justify-end"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </ElCard>
  </div>
</template>

<style scoped>
:deep(.el-table .cell) {
  padding: 0 8px !important;
}

:deep(.el-table__header thead tr:nth-child(2) th) {
  background-color: #fff;
}

/* 筛选表单样式 */
:deep(.el-form-item) {
  margin-bottom: 12px;
}

:deep(.el-form-item__label) {
  padding-bottom: 4px;
  font-size: 12px;
  font-weight: 500;
  line-height: 1.2;
  color: #606266;
}

:deep(.el-input .el-input__wrapper) {
  padding: 0 8px;
}

/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 0;
  margin-right: 2px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
